package com.yyt.module_main.act;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.google.gson.Gson;
import com.yanzhenjie.loading.dialog.LoadingDialog;
import com.yyt.libsrc.bean.PayinfoBean;
import com.yyt.libsrc.conf.Consts;
import com.yyt.libsrc.helper.MsgHelper;
import com.yyt.libsrc.router.RouteTable;
import com.yyt.module_main.R;
import com.yyt.module_main.databinding.ActivityWebpayBinding;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import top.lixb.libcommon.base.RefreshableActivity;
import top.lixb.libcommon.log.L;

@Route(path = RouteTable.main_web_pay)
public class WebpayActivity extends RefreshableActivity<ActivityWebpayBinding> {

    public static final int PAY_WECHAT = 1;
    public static final int PAY_ALIPAY = 2;


    private WebView mWebView;
    private String url;
    private String params;

    @Override
    protected void init() {
        setTitle("支付");
        mSrl.setEnableRefresh(false);
        if (getIntent() != null && getIntent().getExtras() != null) {
            url = getIntent().getStringExtra("url");
            params = getIntent().getStringExtra("params");
        }

        if (TextUtils.isEmpty(url)) {
//            url = "http://admin.huiyie.com/web/html/appPay.html";
//            url = "file:///android_asset/appPay.html";
//            url = Consts.URL.SERVER + "web/html/appPay.html";
            url = "http://pay.veejava.com/wc/pay.do";
        }

        mWebView = mRefreshContentBinding.web;
        WebSettings settings = mWebView.getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
        settings.setTextSize(WebSettings.TextSize.NORMAL);
        //其他细节操作
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        settings.setAllowFileAccess(false); //设置可以访问文件
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式

        // 特别注意：5.1以上默认禁止了https和http混用，以下方式是开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setVerticalScrollbarOverlay(true);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClent());
        mWebView.addJavascriptInterface(new WebAppInterface(), "android");

        String url_str = new String(url.getBytes(), Charset.forName("utf-8"));
        L.e("url:" + url_str);
        mWebView.loadDataWithBaseURL(null, url_str, "text/html", "utf-8", null);

    }

    private class WebAppInterface {

        @JavascriptInterface
        public void gotoNextPage() {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (null != mWebView && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected int initRefreshLayout() {
        return R.layout.activity_webpay;
    }

    @Override
    protected void getData(boolean refresh) {
        finishGetData();
    }

    public String getParams() {
        return params;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now


        if (mWebView != null) {
            mWebView.setWebChromeClient(null);
            mWebView.setWebViewClient(null);
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearCache(true);
            mWebView.removeAllViews();
            try {
                mWebView.destroy();
            } catch (Throwable t) {
                t.printStackTrace();
            }
            mWebView = null;
        }
    }


    private class MyWebChromeClent extends WebChromeClient {
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            // 根据协议的参数，判断是否是所需要的url(原理同方式2)
            // 一般根据scheme（协议格式） & authority（协议名）判断（前两个参数）
            //假定传入进来的 url = "js://webview?arg1=111&arg2=222"（同时也是约定好的需要拦截的）
            L.e("url=" + url + ",message=" + message);
            Uri uri = Uri.parse(message);
            // 如果url的协议 = 预先约定的 js 协议
            // 就解析往下解析参数
            if (uri.getScheme().equals("js")) {
                // 如果 authority  = 预先约定协议里的 webview，即代表都符合约定的协议
                // 所以拦截url,下面JS开始调用Android需要的方法
                if (uri.getAuthority().equals("xbb")) {

                    //
                    // 执行JS所需要调用的逻辑
                    L.e("js调用了Android的方法");
                    // 可以在协议上带有参数并传递到Android上
                    HashMap<String, String> params = new HashMap<>();
                    Set<String> collection = uri.getQueryParameterNames();

                    //参数result:代表消息框的返回值(输入值)
//                    result.confirm(getPayinfo());
                }
                return true;
            }
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            L.e("shoulO loadurl:" + url);


            if (url.startsWith("weixin://wap/pay?")) { //微信支付
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            } else {


                /**
                 * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次 (拦截支付宝支付)
                 */
                final PayTask task = new PayTask(WebpayActivity.this);
                boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                    @Override
                    public void onPayResult(final H5PayResultModel result) {
                        final String url = result.getReturnUrl();
                        String resultCode = result.getResultCode();
                        String resultMsg = "";
                        switch (Integer.valueOf(resultCode)) {
                            case 9000:
                                resultMsg = "订单支付成功";
                                break;
                            case 8000:
                                resultMsg = "正在处理中";
                                break;
                            case 4000:
                                resultMsg = "订单支付失败";
                                break;
                            case 5000:
                                resultMsg = "重复请求";
                                break;
                            case 6001:
                                resultMsg = "用户中途取消";
                                break;
                            case 6002:
                                resultMsg = "网络连接出错";
                                break;
                        }
                        MsgHelper.showToast(resultMsg);
                        if (!TextUtils.isEmpty(url)) {
                            WebpayActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    view.loadUrl(url);
                                }
                            });
                        }
                    }
                });

                L.e("url 拦截成功:" + isIntercepted);
                /**
                 * 判断是否成功拦截
                 * 若成功拦截，则无需继续加载该URL；否则继续加载
                 */
                if (!isIntercepted) {
//                    view.loadUrl(url);
                    Map<String, String> extraHeaders = new HashMap<String, String>();
                    extraHeaders.put("Referer", Consts.Config.testMode ? "http://pay.veejava.com/" : "http://admin.huiyie.com/");
                    view.loadUrl(url, extraHeaders);
                    MsgHelper.showToast("load url" + url);
                }
            }

            return true;
        }
    }

}
